<template>
	<view class="container" v-if="contentShow">
		<view v-if="empty === true" class="empty">
			<image src="/static/emptyCart.jpg" mode="aspectFit"></image>
			<view class="empty-tips">
				<navigator class="navigator" url="../index/index" open-type="switchTab">随便逛逛></navigator>
			</view>
		</view>

		<view v-else>
			<view class="cart-list">
				<block v-for="(item, index) in cartList" :key="index">
					<view
						class="cart-item"
						:class="{ 'b-b': index !== cartList.length - 1 }"
					>
          <view
							class="yticon icon-xuanzhong2 checkbox"
							:class="{checked: item.checked}"
							@click="check('item', index)"
						></view>
						<view class="image-wrapper">
							<image :src="item.img"
								class="loaded"
								mode="aspectFill"
								lazy-load
								@load="onImageLoad('cartList', index)"
								@error="onImageError('cartList', index)"
							></image>
						</view>
						<view class="item-right">
							<text class="clamp title">{{ item.spuName }}</text>
							<text class="attr">{{ item.attr_val }}</text>
							<text class="price">{{ item.amount }} 积分</text>
							<uni-number-box
								class="step"
								:min="1"
								:max="item.stock"
								:value="item.total > item.stock ? item.stock : item.total"
								:isMax="item.total >= item.stock ? true : false"
								:isMin="item.total === 1"
								:index="index"
								@eventChange="numberChange"
							></uni-number-box>
						</view>
            <view class='del-btn'>
              <text class="cuIcon-delete" @click="deleteCartItem(index)"></text>
            </view>
					</view>
				</block>
			</view>

			<view class="action-section">
				<view class="checkbox">
					<image
						:src="allChecked?'/static/selected.png':'/static/select.png'"
						mode="aspectFit"
						@click="check('all')"
					></image>
					<view class="clear-btn" :class="{show: allChecked}">
						全选
					</view>
				</view>
				<view class="total-box">
					<text class="price">合计：{{ total }} 积分</text>
					<!-- <text class="coupon" v-if="isWeiXinType">
						我的积分：
						<text>{{ points }}</text>
					</text> -->
				</view>
				<view class="btn-item">
					<button type="primary" class="no-border confirm-btn btn1" @click="clearCart">清空</button>
					<button type="primary" class="no-border confirm-btn btn2" @click="createOrder">结算</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	import uniNumberBox from '@/components/uni-number-box.vue'
	import { cartGet, cartClear, cartDelete,cartAdd, cartAddApp, cartGetApp, cartClearApp, cartDeleteApp } from 'api/cart'
	import { productInfo, insertUserIntegralReciveRecord, selectUserIntegralById, getOpenidMsg, updateVerification, selectUserIntegralReciveRecordById } from 'api/shop';
	export default {
		components: {
			uniNumberBox
		},
		data() {
			return {
				total: 0, //总价格
				allChecked: false, //全选状态  true|false
				empty: false, //空白页现实  true|false
				cartList: [],
				goodsList: [],
				idCard: '',
				points: '',
				storeId:'',
				userInfo: '',
				buyInfo: {},
				spuId: [],
				contentShow:true,
				isWeiXinType:false
			};
		},

		onShow() {
			console.log('123')
			this.isWeiXin()
			let categoryId = localStorage.getItem("categoryId")
			if(categoryId===''||categoryId===undefined||categoryId===null){
				this.contentShow=false
				this.$api.msg('此链接有误，请重试');
				return false
			}
			this.buyInfo = JSON.parse(localStorage.getItem('buyInfo'))
		},

		// watch:{
		// 	//显示空白页
		// 	cartList(e){
		// 		let empty = e.length === 0 ? true: false;
		// 		if(this.empty !== empty){
		// 			this.empty = empty;
		// 		}
		// 	}
		// },

		computed: {
			...mapState(['hasLogin'])
		},

		methods: {
			isWeiXin () {
			  // window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
			  let ua = window.navigator.userAgent.toLowerCase()
			  // alert(JSON.stringify(ua))
			  // 通过正则表达式匹配ua中是否含有MicroMessenger字符串
			  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				//是公众号
				this.isWeiXinType = true
				this.getOpenidMsgAction();
			  } else {
				//不是公众号
				this.isWeiXinType = false
				this.loadData()
			  }
			},
			getOpenidMsgAction () {
			  getOpenidMsg().then(ret => {
					if (ret.data.errcode === 0) {
						let data = ret.data.data.result
						if (data) {
						if (data.cardNo === null || data.cardNo === '' || data.cardNo === undefined) {
							this.handle()
						} else {
							this.userInfo = data

							this.loadData(data.cardNo)
							this.totalPrice(data.cardNo)
							this.idCard = data.cardNo
						}
						} else {
						this.handle()
						}
					} else if (ret.data.errcode === 9999 || ret.data.errcode === 9991) {
						this.handle()
					} else {
						this.$api.msg(ret.data.errmsg);
						return false
					}
			  })
			},

			handle () {
			  // window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
			  let ua = window.navigator.userAgent.toLowerCase()
			  // 通过正则表达式匹配ua中是否含有MicroMessenger字符串
			  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
				//是微信浏览器
				window.location.href = this.$xeUtils.locat().origin + '/yq/#/handle-submit'
			  } else {
				window.location.href = 'https://shengst.tripln.top/subsidy/#/city-card-handle-app'
			  }
			},

			//监听image加载完成
			onImageLoad(key, index) {
				this.$set(this[key][index], 'loaded', 'loaded');
			},

			//监听image加载失败
			onImageError(key, index) {
				this[key][index].image = '/static/errorImage.jpg';
			},

			navToLogin(){
				uni.navigateTo({
					url: '/pages/public/login'
				})
			},
			 //选中状态处理
			check(type, index){
				if(type === 'item'){
					this.cartList[index].checked = !this.cartList[index].checked;
				}else{
					const checked = !this.allChecked
					const list = this.cartList;
					list.forEach(item=>{
						item.checked = checked;
					})
					this.allChecked = checked;
				}
				this.calcTotal(type);
			},




			// 请求数据
			loadData(param) {
				if(this.isWeiXinType){
					cartGet({
						idCard: param,
						brandId: localStorage.getItem("brandId")
					}).then (ret => {
						if (ret.data.errcode === 0) {
							if (ret.data.data.result === null || ret.data.data.result.length === 0) {
								this.empty = true
								return false
							}else{
								this.empty = false
							}

							this.cartList = ret.data.data.result

							for (var i = 0; i < this.cartList.length; i++) {
								this.cartList[i].checked = true
							}
							console.log(this.cartList,'this.cartList')

							this.calcTotal()
						} else {
							this.$api.msg(ret.data.errmsg)
						}
					})
				}else{
					cartGetApp({
						brandId: localStorage.getItem("brandId")
					}).then (ret => {
						if (ret.data.errcode === 0) {
							if (ret.data.data.result === null || ret.data.data.result.length === 0) {
								this.empty = true
								return false
							}else{
								this.empty = false
							}

							this.cartList = ret.data.data.result

							for (var i = 0; i < this.cartList.length; i++) {
								this.cartList[i].checked = true
							}
							console.log(this.cartList,'this.cartList')

							this.calcTotal()
						} else {
							this.$api.msg(ret.data.errmsg)
						}
					})
				}
			},

			// 获取我的积分总数
			totalPrice(param) {
				selectUserIntegralById({
					idCard: param,
					type:'0',
					brandId: localStorage.getItem("brandId")
				}).then (ret => {
					if (ret.data.errcode === 0) {
						this.points = ret.data.data.totalActivity
						this.storeId = ret.data.data.storeId
					} else {
						this.$api.msg(ret.data.errmsg)
					}
				})
			},

			// 数量
			numberChange(data){
				console.log(data.number,'data.number')
				console.log(this.cartList[data.index].total,'item')
				let num = data.number
				let totalNum = this.cartList[data.index].total
				let number = 0
				if(num>totalNum){
					number = 1
				}else{
					number = -1
				}
				if(this.isWeiXinType){
					if(!this.idCard){
						this.getOpenidMsgAction()
						return false
					}
					cartAdd({
						skuId: this.cartList[data.index].skuId,
						spuId: this.cartList[data.index].spuId,
						deliveryType:this.cartList[data.index].deliveryType,
						supplierId: this.cartList[data.index].supplierId,
						brandId: localStorage.getItem("brandId"),
						spuName: this.cartList[data.index].spuName,
						total: number,
						amount: this.cartList[data.index].amount,
						idCard: this.idCard,
						img: this.cartList[data.index].img
					}).then (ret => {
						if(ret.data.errcode === 0){
							this.loadData(this.idCard)
							// this.$api.msg('添加购物车成功')
						} else {
							this.$api.msg(ret.data.errmsg)
						}
					})
				}else{
					cartAddApp({
						skuId: this.cartList[data.index].skuId,
						spuId: this.cartList[data.index].spuId,
						deliveryType:this.cartList[data.index].deliveryType,
						supplierId: this.cartList[data.index].supplierId,
						brandId: localStorage.getItem("brandId"),
						spuName: this.cartList[data.index].spuName,
						total: number,
						amount: this.cartList[data.index].amount,
						img: this.cartList[data.index].img
					}).then (ret => {
						if(ret.data.errcode === 0){
							this.loadData()
							// this.$api.msg('添加购物车成功')
						} else {
							this.$api.msg(ret.data.errmsg)
						}
					})
				}


				// let JSON = {
				// 	number: data.number,
				// 	id: this.cartList[data.index].spuId
				// }

				// if (this.spuId.length === 0) {
				// 	this.spuId = [...this.spuId, JSON]
				// } else {
				// 	const exist = this.spuId.findIndex((val) => {
				// 	  return val.id === JSON.id
				// 	})

				// 	if (exist === -1) {
				// 		this.spuId = [...this.spuId, JSON]
				// 	} else {
				// 		for (const val of this.spuId) {
				// 			if (val.id === JSON.id) {
				// 				val.number = JSON.number
				// 			}
				// 		}
				// 	}
				// }

				// this.cartList[data.index].number = data.number
				this.calcTotal()
			},

			// 删除购物车商品
			deleteCartItem(index) {
				let list = this.cartList;

				uni.showModal({
					content: '确认删除该商品？',
					success: (e) => {
						if (e.confirm) {
							if(this.isWeiXinType){
								cartDelete({
									idCard: list[index].idCard,
									spuId: list[index].spuId,
									brandId: localStorage.getItem("brandId")
								}).then (ret => {
									if (ret.data.errcode === 0) {
										this.$api.msg('商品删除成功!')

										// this.cartList.splice(index, 1);
										this.calcTotal();
										uni.hideLoading();
										this.loadData(this.cardNo)
									} else {
										this.$api.msg(ret.data.errmsg)
									}
								})
							}else{
								cartDeleteApp({
									idCard: list[index].idCard,
									spuId: list[index].spuId,
									brandId: localStorage.getItem("brandId")
								}).then (ret => {
									if (ret.data.errcode === 0) {
										this.$api.msg('商品删除成功!')

										// this.cartList.splice(index, 1);
										this.calcTotal();
										uni.hideLoading();
										this.loadData(this.cardNo)
									} else {
										this.$api.msg(ret.data.errmsg)
									}
								})
							}
						}
					}
				})
			},

			// 清空购物车
			clearCart() {
				uni.showModal({
					content: '是否确认清空购物车？',
					success: (e) => {
						if (e.confirm) {
							if(this.isWeiXinType){
								cartClear({
									idCard: this.idCard,
									brandId: localStorage.getItem("brandId")
								}).then (ret => {
									if (ret.data.errcode === 0) {
										this.$api.msg('购物车清空成功!')
										this.cartList = [];
										this.empty=true
									} else {
										this.$api.msg(ret.data.errmsg)
									}
								})
							}else{
								cartClearApp({
									brandId: localStorage.getItem("brandId")
								}).then (ret => {
									if (ret.data.errcode === 0) {
										this.$api.msg('购物车清空成功!')
										this.cartList = [];
									} else {
										this.$api.msg(ret.data.errmsg)
									}
								})
							}
						}
					}
				})
			},

			// 计算总价
			calcTotal() {
				let total = 0
				let checked = true

				for (const totalVal of this.cartList) {
					if (totalVal.checked) {
						total += totalVal.amount * (totalVal.number || totalVal.total)
					} else if(checked === true){
						checked = false
					}
				}

				this.allChecked = checked;
				this.total = Number(total.toFixed(2));
			},

			/**
			 * 创建订单 积分结算
			 */
			createOrder() {
				// 如果结算订单大于总积分 禁止结算
				if(this.isWeiXinType){
					if (this.total > this.points) {
						this.$api.msg('积分不足')
						return false
					}
				}

				if (this.spuId.length !== 0) {
					for (const val of this.cartList) {
						for (const key of this.spuId) {
							if (val.spuId === key.id) {
								val.total = key.number
							}
						}
					}
				}

				const arr = this.cartList.map((list) => {
					list.name = list.spuName
					list.supplierId = list.supplierId

					// 解构赋值 获取需要结算参数字段
					let { loaded, spuName, number, ...dataSplit} = list

					dataSplit.mobile = this.userInfo.mobile
					dataSplit.userName = this.userInfo.name
					dataSplit.brandId = localStorage.getItem("brandId")
					dataSplit.storeId = this.storeId

					return dataSplit
				})

				const newArr = arr.filter(item => item.checked === true)

				if(!this.isWeiXinType){
					for (var i = 0; i < newArr.length; i++) {
						delete newArr[i].idCard;
						newArr[i].type = '0'
					}
					console.log(newArr)
					let u = navigator.userAgent
					let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
					if (isAndroid) {
						console.log('isAndroid')
						// JSON.stringify(data)
						//  给Android传递参数需要用 window.Android.注册的方法名({body:传输的数据} 来给native发送消息
						window.Android.getPoints(JSON.stringify(newArr).toString())
					}
				}else{
					// 数据整理完成 跳转订单页面 结算商品
					localStorage.setItem('cartInfo', JSON.stringify(newArr));
					uni.navigateTo({
						url: `/pages/order/cartOrder`
						// url: `/pages/order/cartOrder?data=${
						// 	encodeURIComponent(JSON.stringify(newArr))
						// }`
					})
				}
			}
		}
	}
</script>

<style lang='scss' scoped>
	@import './cart.scss';
</style>
